//
//  UGC_Release_View_WX.m
//  ZITHER
//
//  Created by weixin on 2018/10/11.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "UGC_Release_View_WX.h"
#import "Ugc_Release_VC_WX_V4.h"
#import "Ugc_ReleaseMagazine_VC_WX.h"

#define height1 80

@implementation UGC_Release_View_WX

+ (instancetype)defaultManager {
    
    static UGC_Release_View_WX *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[UGC_Release_View_WX alloc]initWithFrame:CGRectMake(0, kScreenH, kScreenW, kScreenH)];
    });
    return manager;
}


- (void)textViewDidChangeSelection:(UITextView *)textView{
    NSLog(@"字数 : %ld",textView.text.length);
    
    NSInteger textLength = textView.text.length;
    
    if (textLength<120) {
        self.labProgress.hidden = YES;
        self.progressView.hidden = NO;
        self.progressView.progressColor = baseColorRepainting;
        
    }else if (textLength<=140){
        self.labProgress.text = [NSString stringWithFormat:@"%ld",140-textLength];
        self.labProgress.textColor = baseColorRepainting;
        self.labProgress.hidden = NO;
        self.progressView.hidden = NO;
        self.progressView.progressColor = baseColorRepainting;
        
    }else if (textLength<150){
        self.labProgress.text = [NSString stringWithFormat:@"%ld",140-textLength];
        self.labProgress.textColor = baseColorForegroundError;
        self.labProgress.hidden = NO;
        self.progressView.hidden = NO;
        self.progressView.progressColor = baseColorForegroundError;
        
    }else{
        self.labProgress.text = [NSString stringWithFormat:@"%ld",140-textLength];
        self.labProgress.textColor = baseColorForegroundError;
        self.labProgress.hidden = NO;
        self.progressView.hidden =   YES;
        self.progressView.progressColor = baseColorForegroundError;
    }
    
    self.progressView.progressValue = (textLength)/140.0;
    
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        [self addUIBlurEffect];
//        BaseImageV *image = [[BaseImageV alloc]initializeFrame:CGRectMake(0, 0, kScreenW, kScreenH) contentMode:2];
//        image.image = [UIImage imageNamed:@"毛玻璃效果"];
//        image.backgroundColor = [UIColor clearColor];
//        [self addSubview:image];
//        [self setUI];
        [self setUI_v4];
        self.textView.delegate = self;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        
        [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            [self disappearView];
        }];
        self.userInteractionEnabled = YES;
        [self addGestureRecognizer:tap];

    }
    return self;
}

-(void)addUIBlurEffect{
    //毛玻璃
    UIBlurEffect *blurEffect=[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *visualEffectView=[[UIVisualEffectView alloc]initWithEffect:blurEffect];
    [visualEffectView setFrame:self.bounds];
    [self addSubview:visualEffectView];
}

-(void)setUI_v4{
//    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
    
    BaseBtn *btn = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 0,1) NormalImage:@"发布_快速发布" SeleImage:nil];
    [self addSubview:btn];
    btn.backgroundColor = [UIColor clearColor];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self).offset(-140-kBottomSafeHeight-height1);
        make.left.equalTo(self).offset(kScreenW/4.0-35);
        make.height.width.mas_equalTo(70);
    }];
    @weakify(self);
    [[btn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
        
        [UIView animateWithDuration:0.1 animations:^{
            self.frame = CGRectMake(0, -20, kScreenW, kScreenH);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.2 animations:^{
                self.frame = CGRectMake(0, kScreenH, kScreenW, kScreenH);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.1 animations:^{
                    [currentVC.tabBarController.tabBar setHidden:NO];
                    [self.vc.tabBarController.tabBar setHidden:NO];;
                    
                    Ugc_Release_VC_WX_V4 * vc= [[Ugc_Release_VC_WX_V4 alloc]init];
                    [self.getNav pushViewController:vc animated:YES];
                    [self endEditing:YES];
                }];
            }];
        }];

    }];
    
    BaseBtn *btn1 = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 0,1) NormalImage:@"发布_发布杂志" SeleImage:nil];
    [self addSubview:btn1];
    btn1.backgroundColor = [UIColor clearColor];
    [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self).offset(-140-kBottomSafeHeight-height1);
        make.right.equalTo(self).offset(-(kScreenW/4.0-35));
        make.height.width.mas_equalTo(70);
    }];
    
    [[btn1 rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
        
        [UIView animateWithDuration:0.1 animations:^{
            self.frame = CGRectMake(0, -20, kScreenW, kScreenH);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.2 animations:^{
                self.frame = CGRectMake(0, kScreenH, kScreenW, kScreenH);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.1 animations:^{
                    [currentVC.tabBarController.tabBar setHidden:NO];
                    [self.vc.tabBarController.tabBar setHidden:NO];;
                    [self.getNav pushViewController:[[Ugc_ReleaseMagazine_VC_WX alloc]init] animated:YES];

                    [self endEditing:YES];
                }];
            }];
        }];
        

    }];
    
    BaseLab *lab = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 1, 1) text:@"快速发布" font:15 textColor:[UIColor whiteColor] isBold:nil numberOfLines:1];
    lab.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];
    lab.textAlignment = NSTextAlignmentCenter ;
    lab.backgroundColor = [UIColor clearColor];
    [self addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(btn.mas_bottom).offset(15);
        make.centerX.equalTo(btn.mas_centerX).offset(0);
    }];
    
    BaseLab *lab1 = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 1, 1) text:@"发布杂志" font:15 textColor:[UIColor whiteColor] isBold:nil numberOfLines:1];
    lab1.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];
    lab1.textAlignment = NSTextAlignmentCenter ;
    lab1.backgroundColor = [UIColor clearColor];

    [self addSubview:lab1];
    [lab1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(btn1.mas_bottom).offset(15);
        make.centerX.equalTo(btn1.mas_centerX).offset(0);
    }];
    
    BaseLab *lab2 = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 1, 1) text:@"请移步到电脑编辑器" font:12 textColor:[UIColor whiteColor] isBold:nil numberOfLines:1];
    lab2.font = [UIFont fontWithName:@"PingFangSC-Regular" size:12];
    lab2.textAlignment = NSTextAlignmentCenter ;
    lab2.backgroundColor = [UIColor clearColor];

    [self addSubview:lab2];
    [lab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lab1.mas_bottom).offset(10);
        make.centerX.equalTo(btn1.mas_centerX).offset(0);
    }];
    
    
    BaseImageV *image = [[BaseImageV alloc]initializeFrame:CGRectMake(0, 0, 1, 1) contentMode:2];
    image.image = [UIImage imageNamed:@"发布_帮助"];
    image.backgroundColor = [UIColor clearColor];
    [self addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lab2.mas_centerY).offset(0);
        make.left.equalTo(lab2.mas_right).offset(5);
        make.height.width.mas_equalTo(15);
    }];

    
    BaseBtn *btn2 = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 0,1) NormalImage:@"发布_关闭" SeleImage:nil];
    [self addSubview:btn2];
    btn2.backgroundColor = [UIColor clearColor];
    [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self).offset(-10-kBottomSafeHeight);
        make.centerX.equalTo(self.mas_centerX).offset(0);
        make.height.width.mas_equalTo(40);
    }];
    [[btn2 rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self endEditing:YES];
        [self disappearView];
        
        [UIView animateWithDuration:0.1 animations:^{
            self.frame = CGRectMake(0, -20, kScreenW, kScreenH);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.2 animations:^{
                self.frame = CGRectMake(0, kScreenH, kScreenW, kScreenH);
            } completion:^(BOOL finished) {
//                [UIView animateWithDuration:0.1 animations:^{
//                    [currentVC.tabBarController.tabBar setHidden:NO];
//                }];
            }];
        }];
        
    }];

    //发布_发布杂志
    //发布_快速发布
}

-(void)setUI{
    
    QMUIButton *btn = [[QMUIButton alloc]initWithFrame:CGRectMake(14,kStatusBarHeight+5,40,40)];
    [btn setImage:[UIImage imageNamed:@"common_back"] forState:UIControlStateNormal];
    [self addSubview:btn];
    @weakify(self);
    [[btn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self endEditing:YES];
        [self disappearView];
    }];
    
    QMUIButton *btnSend = [[QMUIButton alloc]initWithFrame:CGRectMake(kScreenW-54,kStatusBarHeight+5,40,40)];
    [btnSend setImage:[UIImage imageNamed:@"nav_btn_send"] forState:UIControlStateNormal];
    [self addSubview:btnSend];
    [[btnSend rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        //需要收起键盘
        if (self.textView.text.length<=140) {
            if (self.viewImage.arrM.count != 0 || self.textView.text.length != 0) {
                [self send];
            } else {
                [self endEditing:YES];
                [Tools showTips:@"内容不许为空"];
            }
        }else {
            [self endEditing:YES];
            [Tools showTips:@"字数超过限制"];
        }
        
    }];


    [self addSubview:self.leb];
    [self addSubview:self.textView];
    [self addSubview:self.progressView];
    [self addSubview:self.viewImage];
    [self addSubview:self.labProgress];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.top.equalTo(self.leb.mas_bottom).offset(50);
        make.left.equalTo(self).offset(14);
        make.right.equalTo(self).offset(-14);
        make.height.mas_equalTo(100);
    }];
    
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.top.equalTo(self.textView.mas_bottom).offset(12);
        make.right.equalTo(self).offset(-14);
        make.height.width.mas_equalTo(25);
    }];
    //    self.viewImage.backgroundColor = [UIColor randomColor];
    [self.viewImage mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.top.equalTo(self.progressView.mas_bottom).offset(20);
        make.left.equalTo(self).offset(14);
        make.right.equalTo(self).offset(-14);
        make.height.mas_equalTo(400);
    }];
    
    [self.labProgress mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.center.equalTo(self.progressView).offset(0);
    }];
    
    //    QMUITextView
}

-(QMUILabel *)leb{
    if (!_leb) {
        _leb = [[QMUILabel alloc]initWithFrame:CGRectMake(20,kStatusBarHeight+50, 200, 22)];
        _leb.text = @"新创作";
        _leb.font = [UIFont fontWithName:@"Helvetica-Bold" size:22];
        _leb.textColor = [UIColor blackColor];
    }
    return _leb;
}

-(QMUILabel *)labProgress{
    if (!_labProgress) {
        _labProgress = [[QMUILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
        _labProgress.text = @"1";
        _labProgress.font = [UIFont systemFontOfSize:9];
        _labProgress.textColor = [UIColor blackColor];
        _labProgress.textAlignment = NSTextAlignmentCenter;
        _labProgress.hidden = YES;
        self.progressView.centerView = _labProgress;
    }
    return _labProgress;
}

- (JZProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[JZProgressView alloc]initWithFrame:CGRectMake(100,100, 25, 25)];
        _progressView.layer.backgroundColor = [UIColor whiteColor].CGColor;
        _progressView.progressStrokeWidth = 3.f;
        _progressView.progressValue = 0.01;
        _progressView.progressTrackColor = baseColorLight;
        _progressView.progressColor = baseColorRepainting;
        
    }
    return _progressView;
}

-(QMUITextView *)textView{
    if (!_textView) {
        _textView = [[QMUITextView alloc]initWithFrame:CGRectMake(15, 100, kScreenW-30,300)];
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.placeholder = @"请写点你觉得比较猛的事情,但不要太猛";
        _textView.placeholderColor = baseColorLight; // 自定义 placeholder 的颜色
        _textView.textContainerInset = UIEdgeInsetsMake(10, 7, 10, 7);
        _textView.returnKeyType = UIReturnKeyDone;
        _textView.enablesReturnKeyAutomatically = YES;
        _textView.tintColor = [UIColor blackColor];
        _textView.typingAttributes = @{NSFontAttributeName: UIFontMake(18),
                                       NSForegroundColorAttributeName: [UIColor blackColor],
                                       NSParagraphStyleAttributeName: [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:18]};
        // 限制可输入的字符长度
        _textView.maximumTextLength = 400;
        
        
    }
    return _textView;
}

- (UGCReleaseAddImage *)viewImage{
    if (!_viewImage) {
        _viewImage = [[UGCReleaseAddImage alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 300)];
    }
    return _viewImage;
}




#pragma mark - 上传图片
- (void)uploadImageWithPhotos:(NSArray<UIImage *> *)photos completion:(AskImageUploadBlock)completion {
    //  开启菊花
    //    [QMUITips showLoadingInView:self.view];
    // 调度组
    dispatch_group_t group = dispatch_group_create();
    // 队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    __block NSMutableArray<NSString *> *uploadURLs = @[].mutableCopy;
    
    
    self.arrMName = [[NSMutableArray alloc]init];
    NSString *date = [NSString currentDateDateFormatter:@"yyyyMM"];
    NSString *path =[NSString stringWithFormat:@"/ugc/%@",date];
    NSString *Timestamp = [Tools getCurrentTimestamp];

    for (int i = 0; i<photos.count; i++) {
        
        /** 设置名称 */
        
        NSString *imageType = [Tools contentTypeWithImage:photos[i]];

        NSString * fileName1 = [NSString stringWithFormat:@"%@_%@_%d.%@",kUSER_INFO_MANAGER.userId,Timestamp,i,imageType];
        [self.arrMName addObject:fileName1];

    }

 

    for (NSUInteger i = 0; i< photos.count; i++) {

        UIImage *image = [photos objectAtIndex:i];
        
        //分别开组
        dispatch_group_enter(group);
        dispatch_group_async(group, queue, ^{

            @weakify(uploadURLs);
            ///ugc/201810/0B374CCAD80711E89B155254005876C0_1540446908_0.png
            ///ugc/201810/0B374CCAD80711E89B155254005876C0_1540446945_2.png
            ///ugc/201810/0B374CCAD80711E89B155254005876C0_1540446957_1.png
            ///ugc/201810/0B374CCAD80711E89B155254005876C0_1540447001_3.png
            ///ugc/201810/0B374CCAD80711E89B155254005876C0_1540447929_0.png,
            ///ugc/201810/0B374CCAD80711E89B155254005876C0_1540447929_3.png,
            ///ugc/201810/0B374CCAD80711E89B155254005876C0_1540447929_1.png,
            ///ugc/201810/0B374CCAD80711E89B155254005876C0_1540447929_2.png
//            [kNetworkShared getImageURLWithImageOld:image Path:path batchIndex:i completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
//                @strongify(uploadURLs);
//                if (isSuccess) {
//                    [uploadURLs addObject:kSTRING_FORMAT(@"%@/%@",filePath, fileName)];
//                }
//                dispatch_group_leave(group);
//            }];
            [kNetworkShared getImageURLWithImage:image Path:path fileName:self.arrMName[i] batchIndex:i Timestamp:Timestamp completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
                @strongify(uploadURLs);
                if (isSuccess) {
                    [uploadURLs addObject:kSTRING_FORMAT(@"%@/%@",filePath, fileName)];
                }else{
                    [Tools showTips:error];
                }
                dispatch_group_leave(group);
            }];
 



            
        });
    }
//    //完成通知
//    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//        //        [QMUITips hideAllTipsInView:self.view];
//        if (uploadURLs.count == photos.count) {
////            NSString *imgURLs = [uploadURLs componentsJoinedByString:@","];
//            // 全部上传成功
//
//            for (int i = 0; i<self.arrMName.count; i++) {
//                self.arrMName[i] = kSTRING_FORMAT(@"%@/%@",path, self.arrMName[i]);
//            }
//            [[serviceDefualt loadGetAddUserUgc:self.textView.text fileList:self.arrMName userSubjectId:self.TopicID reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
//
//
////            [[serviceDefualt loadGetAddUserUgc:self.textView.text fileList:self.arrMName userSubjectId:self.TopicID reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
//                if (x.success) {
//                    if (completion) {
//                        completion(YES, nil);
//                    }
//                }else{
//                    if (completion) {
//                        completion(NO, nil);
//                    }
//                }
//            }];
//            /** 旧的写法 */
////            [[ serviceDefualt loadGetAddUserUgc:self.textView.text fileList:uploadURLs userSubjectId:self.TopicID reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
////                if (x.success) {
////                    if (completion) {
////                        completion(YES, nil);
////                    }
////                }else{
////                    if (completion) {
////                        completion(NO, nil);
////                    }
////                }
////            }];
//
//        } else {
//            if (completion) {
//                completion(NO, nil);
//            }
//        }
//    });
}


-(void)send{
    
    UgcReleaseFailureModel *modelson = [[UgcReleaseFailureModel alloc]init];
    modelson.content = self.textView.text;
    modelson.arrMPic = [[NSMutableArray alloc]init];
    [self endEditing:YES];
    [self disappearView];
    
    //是否有图片
    if (self.viewImage.arrM.count > 0) {
        //有图片  先上传图片
        for (int i =0; i<self.viewImage.arrM.count; i++) {
            [modelson.arrMPic addObject:self.viewImage.arrM[i]];
        }
        @weakify(self);
        [self uploadImageWithPhotos:self.viewImage.arrM.copy completion:^(BOOL isSuccess, NSString *imageURLs) {
            @strongify(self);
            if (isSuccess) {
                [Tools showTips:@"发送成功"];
//                [self endEditing:YES];
//                [self disappearView];
            } else {
                [kUSER_INFO_MANAGER addFailureModel:modelson];
                [Tools showTips:@"发送失败"];
//                [self disappearView];
            }
        }];
    }else{
        //没图片
        @weakify(self);
//        [[ serviceDefualt loadGetAddUserUgc:self.textView.text fileList:nil userSubjectId:self.TopicID reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
//            @strongify(self);
//            if (x.success) {
//                [Tools showTips:@"发送成功"];
////                [self endEditing:YES];
////                [self disappearView];
//            }else{
//                
//                [kUSER_INFO_MANAGER addFailureModel:modelson];
//                [Tools showTips:@"发送失败"];
////                [self disappearView];
//            }
//            
//        }];
    }
}

-(void)disappearView{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    
    [UIView animateWithDuration:0.1 animations:^{
        self.frame = CGRectMake(0, -20, kScreenW, kScreenH);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 animations:^{
            self.frame = CGRectMake(0, kScreenH, kScreenW, kScreenH);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.1 animations:^{
                [currentVC.tabBarController.tabBar setHidden:NO];
                [self.vc.tabBarController.tabBar setHidden:NO];;
                
//                Ugc_Release_VC_WX_V4 * vc= [[Ugc_Release_VC_WX_V4 alloc]init];
//                [self.getNav pushViewController:vc animated:YES];
//                [self endEditing:YES];
            }];
        }];
    }];
}

- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    } else {
        // 根视图为非导航类
        
        currentVC = rootVC;
    }
    
    return currentVC;
}

-(void)cleanData{
    self.textView.text = @"";
    [self.viewImage cleanData];
}

-(BOOL)iseqHidden{
    if (DEFAULReleaseV.frame.origin.y==0) {
        NSLog(@"显示");
        return NO;
    }
    NSLog(@"");
    return YES;
}

@end
